import { Button, Table, notification } from "antd";
import axios from "axios";
import React, { useState, useEffect } from "react";

export default function Audit() {
  const [dataSource, setdataSource] = useState([]);
  const { roleId, region, username } = JSON.parse(
    localStorage.getItem("token")
  );

  // 请求回项目中所有需要审核的新闻，不仅仅是超级管理员的，然后进行筛选
  useEffect(() => {
    const roleObj = {
      1: "superadmin",
      2: "admin",
      3: "editor",
    };
    // auditState=1代表新闻是审核中的状态带着列表查询
    axios.get(`/news?auditState=1&_expand=category`).then((res) => {
      const list = res.data;
      // console.log(list);
      list.forEach((item) => {
        if (item.label) {
          item.title = item.label;
        }
      });
      //哪些能显示 如果是超级管理员 就都可以显示
      setdataSource(
        roleObj[roleId] === "superadmin"
          ? list
          : [
              ...list.filter((item) => item.author === username),
              // 再过滤出同一个区域，并且是同一区域下的小编辑
              ...list.filter(
                (item) =>
                  item.region === region && roleObj[item.roleId] === "editor"
              ),
            ]
      );
    });
  }, [roleId, region, username]);
  const columns = [
    {
      title: "新闻标题",
      dataIndex: "title",
      render: (title, item) => (
        <a href={`/news-manage/preview/${item.id}`}>{title}</a>
      ),
    },
    {
      title: "作者",
      dataIndex: "author",
    },
    {
      title: "新闻分类",
      dataIndex: "category",
      render: (category) => <div color="orange">{category.label}</div>,
    },
    {
      title: "操作",
      render: (row) => {
        return (
          <div>
            <Button type="primary" onClick={() => handleAduit(row, 2, 1)}>
              通过
            </Button>
            <Button danger onClick={() => handleAduit(row, 3, 0)}>
              驳回
            </Button>
          </div>
        );
      },
    },
  ];
  // 通过/驳回按钮的回调函数
  const handleAduit = (row, auditState, publishState) => {
    // 先把当前一项移除掉
    setdataSource(dataSource.filter((item) => item.id !== row.id));
    // 进行补丁的更新
    axios
      .patch(`/news/${row.id}`, {
        auditState,
        publishState,
      })
      .then(() => {
        notification.info({
          message: "通知",
          description: `您可以去【审核管理/审核列表】中查看`,
          placement: "bottomRight",
        });
      });
  };
  return (
    <div>
      <Table
        dataSource={dataSource}
        columns={columns}
        rowKey={(item) => item.id}
        pagination={{ pageSize: 5 }}
      ></Table>
    </div>
  );
}
